package com.person.pay.controller;

import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayResponse;
import com.person.pay.pojo.PayInfo;
import com.person.pay.service.impl.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 最酷的桃儿wjc
 * * @date 2022/5/9
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {
    @Autowired
    private PayService payService;
    @Autowired
    private WxPayConfig wxPayConfig;
    //发起支付的API，用来返回可以被用户支付的界面
    @GetMapping("/create")
    public ModelAndView create(
            @RequestParam("orderId") String orderId,
            @RequestParam("amount") BigDecimal amount,
            @RequestParam("payType") BestPayTypeEnum bestPayTypeEnum
            ){
        PayResponse response = payService.create(orderId, amount,bestPayTypeEnum);
        //将地址信息存到Map集合中
        Map<String,String> map = new HashMap();
        //支付方式不同渲染的方式不同，微信支付使用URL，支付宝支付使用body
        if(bestPayTypeEnum == BestPayTypeEnum.WXPAY_NATIVE){
            map.put("code_url",response.getCodeUrl());
            map.put("orderId",orderId);
            map.put("returnUrl",wxPayConfig.getReturnUrl());
            return new ModelAndView("createForWxNative",map);
        } else if (bestPayTypeEnum == BestPayTypeEnum.ALIPAY_PC){
            map.put("body",response.getBody());
            return new ModelAndView("createAliPayForPC",map);
        }
        throw new RuntimeException("不支持该支付类型");
    }
    //异步通知处理
    @PostMapping("/notify")
    @ResponseBody
    public String asyncNotify(@RequestBody String notifyData){
        return payService.asyncNotify(notifyData);
    }



    //支付完成，通过订单号查询支付状态的API
    @GetMapping("/queryByOrderNo")
    @ResponseBody
    public PayInfo queryByOrderNo(@RequestParam("orderId") String orderNo){
        return payService.queryByOrderNo(orderNo);
    }


}
